<template>
    <div class="attr-detail">
        <h1>商品规格</h1>
        <attr ref='attr' :product-info='productInfo'/>
        <el-table
            :data="tableData"
            :span-method="objectSpanMethod"
            stripe
            border
            :header-cell-style="TABLE_HEADER_CELL_STYLE">
            <template v-if="tableHeader.length">
                <el-table-column 
                    v-for='(item,index) in tableHeader' 
                    :key='index'
                    :label='item.key_name' :prop='`${item.id}`'></el-table-column>
            </template>
            <el-table-column label='库存' prop='count'>
                <template v-slot='scope'>
                    <el-input v-model='scope.row.stock_number' type='number'></el-input>
                </template>
            </el-table-column>
            <el-table-column label='会员价' prop='count'>
                <template v-slot='scope'>
                    <el-input v-model='scope.row.member_price' type='number'></el-input>
                </template>
            </el-table-column>
            <el-table-column label='市场价' prop='count'>
                <template v-slot='scope'>
                    <el-input v-model='scope.row.market_price' type='number'></el-input>
                </template>
            </el-table-column>
            <el-table-column label='预览图' prop='count'>
                <template v-slot='scope'>
                    <o-upload v-model="scope.row.sku_img_url" :width='60'></o-upload>
                    <!-- <el-input v-model='scope.row.sku_img'></el-input> -->
                </template>
            </el-table-column>
            <el-table-column label='SKU编码' prop='count'>
                <template v-slot='scope'>
                    <el-input v-model='scope.row.sku_code' ></el-input>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
    import {nanoid} from 'nanoid';
    import attr from './attr';
    import mergeCell from "@u/mergeCell"; 
    import { mapState } from 'vuex'
    import {PRODUCT_PARAMS} from '@const';
    import {toast} from '@u';
    export default {
        components : {
            attr
        },
        props : {
            productInfo : {
                type : Object,
                default : _ => {}
            }
        },
        watch : {
            productInfo (n) {
                if (n.id) {
                    this.tableData = n.specs_combination_json.map(item => {
                        item = {
                            ...item,
                            ...item.specs_json
                        }
                        return item;
                    })
                }
            }
        },
        provide () {
            return {
                parent : this
            }
        },
        computed : {
            ...mapState(['product']),
            tableHeader () {
                this.spanArr = mergeCell(this.product.selectAttrTypeOptions.map(item => `${item.id}_value_id`), this.tableData);
                return this.product.selectAttrTypeOptions;
            }
        },
        data () {
            return {
                spanArr: [],//用于存放每一行记录的合并数
                tableData: []
            }
        },
        created () {
            
        },

        methods : {

            objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
                if (columnIndex < this.spanArr.length) {
                    const _row = this.spanArr[columnIndex][rowIndex];
                    const _col = _row > 0 ? 1 : 0; //如果被合并了_row=0则它这个列需要取消
                    return {
                        rowspan: _row,
                        colspan: _col
                    };
                }
            },
            //规格值被删除
            _attrValueDelete (attrItem) {

                this.tableData = this.tableData.filter(item => item[`${attrItem.id}_value_id`] != attrItem[`${attrItem.id}_value_id`])
            },
            //规格值改变
            _attrValueChange (attrItem) {
                //初始化
                if (!this.tableData.length) {
                    this.tableData = [
                        {
                            [`${attrItem.id}`] : attrItem[attrItem.id],
                            [`${attrItem.id}_value_id`] : attrItem[`${attrItem.id}_value_id`],
                        }
                    ]
                    return;
                }
                //如果已经有存在相应的值，只做更新操作
                if (this.tableData.some(item => item[`${attrItem.id}_value_id`] == attrItem[`${attrItem.id}_value_id`])) {
                    this.tableData = this.tableData.map(item => {
                        if (item[`${attrItem.id}_value_id`] == attrItem[`${attrItem.id}_value_id`]) {
                            item[`${attrItem.id}`] = attrItem[attrItem.id];
                        }
                        return item;
                    });
                    return;
                }
                //如果只选了一种规格，只要push新的规格数据进去就行
                if (this.product.selectAttrIds.length == 1) {
                    this.tableData = [...this.tableData, {
                        [`${attrItem.id}`] : attrItem[attrItem.id],
                        [`${attrItem.id}_value_id`] : attrItem[`${attrItem.id}_value_id`],
                    }];
                    return;
                }

                //当前新家的规格不在当前数据中
                if (this.tableData.every(item => !item[`${attrItem.id}`])) {
                    this.tableData = this.tableData.map(item => {
                        return {
                            ...item,
                            [`${attrItem.id}`] : attrItem[attrItem.id],
                            [`${attrItem.id}_value_id`] : attrItem[`${attrItem.id}_value_id`],
                        }
                    });
                    return;
                }
                //获取在当前数据之前的组件内的atrs，并且重新重新合并
                this._reLoadTabelData();
            },
            //重新排列表格数据
            _reLoadTabelData () {
                let _pre_attrs = this.$refs.attr.$refs.attrItem.map(v => {
                    return v.attrs.filter(t => t[t.id])
                });
                this.tableData = this._doExchange(_pre_attrs).map(item => {
                    return {
                        ...item,
                        ...PRODUCT_PARAMS
                    }
                });
            },
            //排列组合规格
            _doExchange (arr) {
                if (arr.length == 1) {
                    return arr[0][0].id ? arr[0].map(item => {
                        return {
                            [`${item.id}`] : item[item.id],
                            [`${item.id}_value_id`] : item[`${item.id}_value_id`]
                        }
                    }) : arr[0];
                } else {
                    let len1 = arr[0].length;
                    let len2 = arr[1].length;
                    let newArr = [];
                    for (let i = 0; i < len1; i ++) {
                        for (let j = 0; j < len2; j ++) {

                            let params = arr[0][i].id ? {
                                [`${arr[0][i].id}`] : arr[0][i][arr[0][i].id],
                                [`${arr[0][i].id}_value_id`] : arr[0][i][`${arr[0][i].id}_value_id`],
                                [`${arr[1][j].id}`] : arr[1][j][arr[1][j].id],
                                [`${arr[1][j].id}_value_id`] : arr[1][j][`${arr[1][j].id}_value_id`],
                            } : {
                                ...arr[0][i],
                                [`${arr[1][j].id}`] : arr[1][j][arr[1][j].id],
                                [`${arr[1][j].id}_value_id`] : arr[1][j][`${arr[1][j].id}_value_id`],
                            }
                            newArr.push(params)
                        }
                    }
                    arr.splice(0,2);
                    arr.unshift(newArr);
                    return this._doExchange(arr)
                }
            },
            //getPerpertiesData
            getPerpertiesData () {
                // 验证规格属性都填写了
                let check = this.tableData.every(item => {
                    return item.stock_number && item.member_price && item.market_price && item.sku_img_url && item.sku_code
                })
                if (!check) {
                    return false;
                }

                let specs_combination_json = JSON.parse(JSON.stringify(this.tableData));
                const selectAttrIds = this.product.selectAttrIds.map(v => String(v));
                //梳理成后端需要的格式
                if (specs_combination_json.length) {
                    specs_combination_json.map(item => {
                        item.specs_json = {}
                        for (let key in item) {
                            if (selectAttrIds.includes(key)) {
                                item.specs_json[key] = item[key];
                                item.specs_json[`${key}_value_id`] = item[`${key}_value_id`];
                                delete item[key]
                                delete item[`${key}_value_id`]
                            }
                        }
                    })
                }

                return {
                    specs_combination_json,
                    specs_select_json :  this.$refs.attr.getAttrValues().map(v => {
                        v.attrs = v.attrs.filter(item => item[`${item.id}`])
                        return v
                    })
                };
            }
        }
    }
</script>

<style lang='less' scoped>
    .attr-detail {
        padding: 15px;
        background: #f5f5f5;
    }
</style>